package com.example.administrator.printoutindemo.mvp.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.example.administrator.printoutindemo.R;
import com.example.administrator.printoutindemo.adapter.RuKuSuccessAdapter;
import com.example.administrator.printoutindemo.bean.RukuSuccessBean;
import com.example.administrator.printoutindemo.di.component.DaggerRuKuChengGongJiLuComponent;
import com.example.administrator.printoutindemo.di.module.RuKuChengGongJiLuModule;
import com.example.administrator.printoutindemo.http.SPUtil;
import com.example.administrator.printoutindemo.mvp.contract.RuKuChengGongJiLuContract;
import com.example.administrator.printoutindemo.mvp.presenter.RuKuChengGongJiLuPresenter;
import com.example.administrator.printoutindemo.mvp.ui.entity.RuKuChengGongJiLu;
import com.example.administrator.printoutindemo.mvp.ui.view.RuKuChengGongRightSideslipLay;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import com.jess.arms.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.Utils;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ACTIVITY_RU_KU_CHENG_GONG_JI_LU)
public class RuKuChengGongJiLuActivity extends BaseActivity<RuKuChengGongJiLuPresenter> implements RuKuChengGongJiLuContract.View, RuKuChengGongRightSideslipLay.FlowingDrawerInterface, OnRefreshListener, OnLoadMoreListener, RuKuSuccessAdapter.IRuKuSuccessAdapter {
    @BindView(R.id.btnRight)
    TextView mBtnRight;
    @BindView(R.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    @BindView(R.id.drawer_layout)
    DrawerLayout mDrawer;
    @BindView(R.id.nav_view)
    LinearLayout navigationView;
    @BindView(R.id.empty)
    View mEmptyLayout;
    @BindView(R.id.empty_text)
    TextView empty_text;
    @BindView(R.id.empty_image)
    ImageView empty_image;
    private EditText et_ddh, et_ddmc, et_wlmc, et_gys, et_cwmc;
    private ListView lv_liebiao;
    private List<RukuSuccessBean> mmlist;
    private RuKuSuccessAdapter mAdapter;
    private TextView tv_chaxun;
    private RuKuChengGongRightSideslipLay menuHeaderView;
    private String mDingDanHao = "";
    private String mXiangMuMingCheng = "";
    private String mXiangMuBianMa = "";
    private String mWuLiaoMingCheng = "";
    private String mGongYingShangMingCheng = "";
    private String mCangWeiMingCheng = "";
    private boolean mIsCheck = false;

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        getInstoreHistoryForAndroid(mDingDanHao, mXiangMuMingCheng, mXiangMuBianMa, mWuLiaoMingCheng, mGongYingShangMingCheng, mCangWeiMingCheng, mIsCheck);
        mRefreshLayout.finishLoadMore();
    }

    private void getInstoreHistoryForAndroid(String dingDanHao, String xiangMuMingCheng, String xiangMuBianMa, String wuLiaoMingCheng, String gongYingShangMingCheng, String cangWeiMingCheng, boolean isCheck) {

        showLoading();

        String methodName = "InstoreHistoryForAndroidPaging";

        SoapParams params = new SoapParams();
        params.put("uid", SPUtil.getString(getContext(), "iduser", ""));//用户id
        params.put("projectName", xiangMuMingCheng);//项目名称
        params.put("supplierName", gongYingShangMingCheng);//供应商名称
        params.put("material", wuLiaoMingCheng);//物料名称
        params.put("purchaseid", dingDanHao);//订单号
        params.put("spname", cangWeiMingCheng);//仓位名称
        params.put("startIndex", String.valueOf(mStart));
        params.put("endIndex", String.valueOf(mStart + mNum - 1));

        /**
         * 请求
         */
        SoapUtil.getInstance(getContext()).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    mAdapter.shua();
                    List<RukuSuccessBean> rukuSuccessBeen = new Gson().fromJson(result, new TypeToken<List<RukuSuccessBean>>() {
                    }.getType());
                    if (rukuSuccessBeen != null && rukuSuccessBeen.size() > 0) {
                        mStart += rukuSuccessBeen.size();
                        lv_liebiao.setVisibility(View.VISIBLE);
                        mEmptyLayout.setVisibility(View.GONE);
                        mAdapter.addAll(rukuSuccessBeen);
                    }
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
                ArmsUtils.makeText(getContext(), error.getMessage());

            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());

    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerRuKuChengGongJiLuComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .ruKuChengGongJiLuModule(new RuKuChengGongJiLuModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_ru_ku_cheng_gong_ji_lu; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_ru_ku_cheng_gong_ji_lu));
//        getRuKuChengGongJiLuData();
        initBtnRight();
        initEmpty();
        initRefreshLayout();
        initView1();


        initDeawer();

        getInstoreHistoryForAndroid("", "", "", "", "", "", false);

    }

    private void initBtnRight() {
        mBtnRight.setText("筛选");
        mBtnRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openMenu();
            }
        });
    }

    private void initEmpty() {
        empty_image.setImageResource(com.xiaoxing.zhinenghuacangku.R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("暂无数据");
    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new
                ClassicsHeader(this).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(com.xiaoxing.zhinenghuacangku.R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadMoreListener(this);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setEnableLoadMore(true);
    }

    private void initView1() {
        et_ddh = findViewById(R.id.et_ddh);
        et_ddmc = findViewById(R.id.et_ddmc);
        et_wlmc = findViewById(R.id.et_wlmc);

        et_gys = findViewById(R.id.et_gys);
        et_cwmc = findViewById(R.id.et_cwmc);
        tv_chaxun = findViewById(R.id.tv_chaxun);
        lv_liebiao = findViewById(R.id.lv_liebiao);
        mmlist = new ArrayList<>();
        mAdapter = new RuKuSuccessAdapter(this, mmlist, this);
        lv_liebiao.setAdapter(mAdapter);
        tv_chaxun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

//                getInstoreHistoryForAndroid(et_ddh.getText().toString(), et_ddmc.getText().toString(), "", et_wlmc.getText().toString(), et_gys.getText().toString(), et_cwmc.getText().toString());

            }
        });
    }

    private void initDeawer() {
        mDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);

        menuHeaderView = new RuKuChengGongRightSideslipLay(RuKuChengGongJiLuActivity.this, this);
        navigationView.addView(menuHeaderView);

        menuHeaderView.setCloseMenuCallBack(new RuKuChengGongRightSideslipLay.CloseMenuCallBack() {
            @Override
            public void setupCloseMean() {
                closeMenu();
            }
        });
    }

    public void openMenu() {
        mDrawer.openDrawer(GravityCompat.END);
    }

    public void closeMenu() {
        mDrawer.closeDrawer(GravityCompat.END);
    }

    @Subscriber(tag = "updateRuKuChengGongJiLu", mode = ThreadMode.MAIN)
    public void updateRuKuChengGongJiLu(String msg) {

        mEmptyLayout.setVisibility(View.VISIBLE);
        lv_liebiao.setVisibility(View.GONE);
        mAdapter.clearData();
        mStart = 1;

        getInstoreHistoryForAndroid("", "", "", "", "", "", false);

    }

    private void getRuKuChengGongJiLuData() {
        mPresenter.getRuKuChengGongJiLuData();
    }

    @Override
    public void getRuKuChengGongJiLuDataSuccess(RuKuChengGongJiLu entityData) {


    }

    @Override
    public void flowingDrawerClose() {
        closeMenu();
    }

    @Override
    public void search(String dingDanHao, String xiangMuMingCheng, String xiangMuBianMa, String wuLiaoMingCheng, String gongYingShangMingCheng, String cangWeiMingCheng, boolean isCheck) {
        mEmptyLayout.setVisibility(View.VISIBLE);
        lv_liebiao.setVisibility(View.GONE);
        mAdapter.clearData();

        mStart = 1;
        mDingDanHao = dingDanHao;
        mXiangMuMingCheng = xiangMuMingCheng;
        mXiangMuBianMa = xiangMuBianMa;
        mWuLiaoMingCheng = wuLiaoMingCheng;
        mGongYingShangMingCheng = gongYingShangMingCheng;
        mCangWeiMingCheng = cangWeiMingCheng;
        mIsCheck = isCheck;

        closeMenu();
        mAdapter.clearData();

        getInstoreHistoryForAndroid(dingDanHao, xiangMuMingCheng, xiangMuBianMa, wuLiaoMingCheng, gongYingShangMingCheng, cangWeiMingCheng, isCheck);
    }

    @Override
    public void modifyRenark(RukuSuccessBean rukuSuccessBean, String remark) {
        Bundle bundle = new Bundle();
        bundle.putString("mid", String.valueOf(rukuSuccessBean.getMid()));
        bundle.putString("remark", remark);
        Utils.navigation(this, RouterHub.ACTIVITY_XIU_GAI_BEI_ZHU, bundle);

//        updRemarkByMid(String.valueOf(rukuSuccessBean.getMid()), remark);
    }

    private void updRemarkByMid(String mid, String remark) {

        showLoading();

        String methodName = "updRemarkByMid";

        SoapParams params = new SoapParams();
        params.put("mid", mid);//用户id
        params.put("remark", remark);//项目名称

        /**
         * 请求
         */
        SoapUtil.getInstance(getContext()).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    showMessage("备注修改成功");
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
                ArmsUtils.makeText(getContext(), error.getMessage());

            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());

    }

}
